<template>
  <div>
    <el-card class="box-card" shadow="false">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
        <el-button
          style="float: right"
          type="primary"
          size="mini"
          @click="handleSave"
          >{{ $t("common.save") }}</el-button
        >
      </div>
      <div class="text item">
        <permission-tree
          v-model="checkedPermissionKeys"
          :role="role"
          ref="tree"
        ></permission-tree>
      </div>
    </el-card>
  </div>
</template>
<script>
import permissionTree from "@/components/Tree/permissionTree.vue";
import { updateRolePermissions, getRolePermissions } from "@/api/role";
export default {
  components: {
    permissionTree,
  },
  data() {
    return {
      checkedPermissionKeys: [],
    };
  },
  methods: {
    getData() {
      this.checkedPermissionKeys = [];
      this.setRolePermissions(this.role.name);
    },
    setRolePermissions(name) {
      getRolePermissions(name).then((res) => {
        let groups = res && res.groups ? res.groups : [];

        if (!groups || groups.length == 0) return;

        let grantedPermissions = this.getGrantPermissionItems(groups);
        this.checkedPermissionKeys = grantedPermissions
          ? grantedPermissions.map((permission) => {
              return permission.name;
            })
          : [];
      });
    },
    getGrantPermissionItems(groups) {
      //这个方法主要是用于去掉父级授予的权限项，因为el-tree父级选中，会把子级全部选中，从而导致显示错误
      let leafPermissionItems = this.$refs.tree.getLeafItems();
      let laftPermissionItemNames = leafPermissionItems.map((x) => x.code);
      let grantedPermissions = [];

      for (let i = 0; i < groups.length; i++) {
        grantedPermissions = grantedPermissions.concat(groups[i].permissions);
      }

      grantedPermissions = grantedPermissions.filter((value) => {
        return value.isGranted && laftPermissionItemNames.includes(value.name);
      });

      return grantedPermissions;
    },
    handleSave() {
      let checkedKeys = this.checkedPermissionKeys;
      let postData = this.getPostData(checkedKeys);

      if (checkedKeys.length == 0) {
        this.$confirm(
          this.$t("tips.confirmCancelPermission"),
          this.$t("common.tips"),
          {
            confirmButtonText: this.$t("common.ok"),
            cancelButtonText: this.$t("common.cancel"),
            type: "warning",
          }
        )
          .then(() => {
            this.savePermission(postData);
          })
          .catch(() => {});
      } else {
        this.savePermission(postData);
      }
    },
    savePermission(permissions) {
      updateRolePermissions(permissions, this.role.name).then((res) => {
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
          position: "bottom-right",
        });
        this.getData();
      });
    },
    getPostData() {
      let result = [];

      let permissionItems = this.$refs.tree.getItems();

      if (!permissionItems || permissionItems.length == 0) return result;

      for (let i = 0; i < permissionItems.length; i++) {
        let name = permissionItems[i].code;

        let matchKey = this.checkedPermissionKeys.find((key) => {
          return key == permissionItems[i].code;
        });
        result.push({ name: name, isGranted: matchKey ? true : false });
      }
      return result;
    },
  },
  mounted() {
    this.getData();
  },
  watch: {},
  props: {
    role: {
      type: Object,
      default: () => {},
    },
    title: {
      type: String,
      default: "",
    },
  },
};
</script>
